﻿package cn.hadron.ssh.dao.impl;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import cn.hadron.ssh.dao.*;
import cn.hadron.ssh.util.Pager;
import cn.hadron.ssh.bean.*;
public class ArticleDaoImpl implements ArticleDao{
	private SessionFactory sessionFactory;
	private Session session;
	
	// 增删改操作，需要事务处理
	@Override
	public  void add(Article article) {
		getSession().clear();
		getSession().beginTransaction();
		getSession().save(article);
		getSession().getTransaction().commit();
	}
	@Override
	public  void update(Article article) {
		getSession().clear();
		getSession().beginTransaction();
		getSession().update(article);// 对应于load()加载对象
		getSession().getTransaction().commit();
	}
	@Override
	public  void delete(int id) {
		getSession().beginTransaction();
		Article a = (Article)getSession().load(Article.class, id);
		getSession().delete(a);
		getSession().getTransaction().commit();
	}	

	// 查询不需要事务处理
	@Override
	public  Article load(int id) {
		return (Article)getSession().load(Article.class, id);
	}
	@Override
	public  List<Article> findAll() {
		String hql = "from Article";
		List<Article> list = getSession().createQuery(hql,Article.class).list();
		return list;
	}

    public int getCount(String hql) {
    	try{
    		return getSession().createQuery(hql).list().size();
		} catch (Exception e) {
			System.out.println("getCount："+e);
			return 0;
		}
    }
    @Override
    public Pager<Article> findPager(int pageNo,int pageSize){
    	String hql="from Article order by id asc";
    	final Pager<Article> pager = new Pager<Article>(pageNo, pageSize, this.getCount(hql));
        List<Article> list = getSession().createQuery(hql,Article.class)
        		.setFirstResult((pageNo-1)*pageSize)
        		.setMaxResults(pageSize).list();
		pager.setData(list);
		return pager;
    }
    @Override
	public  Pager<Article> findPager(int channelId,int pageNo,int pageSize) {
		getSession().clear();
		String hql="from Article where channel.id=? order by id asc";
		final Pager<Article> pager = new Pager<Article>(pageNo, pageSize, this.getCount(hql));
        List<Article> list = getSession().createQuery(hql,Article.class)
        		.setParameter(0, channelId)
        		.setFirstResult((pageNo-1)*pageSize)
        		.setMaxResults(pageSize).list();
		pager.setData(list);
		return pager;
	}
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	public Session getSession() {
		if (null == session || false == session.isOpen())
			session = sessionFactory.openSession();
		return session;
	}
	public void setSession(Session session) {
		this.session = session;
	}
}